#!/usr/bin/python

"""Project Euler Solution 030

Copyright (c) 2011 by Robert Vella - robert.r.h.vella@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import cProfile
from euler.numbers.decimal_base import integer_to_digits

def get_answer():
    """Question:
    
    Surprisingly there are only three numbers that can be written as the 
    sum of fourth powers of their digits:
    
    1634 = 1**4 + 6**4 + 3**4 + 4**4
    8208 = 8**4 + 2**4 + 0**4 + 8**4
    9474 = 9**4 + 4**4 + 7**4 + 4**4
    As 1 = 1**4 is not a sum it is not included.

    The sum of these numbers is 1634 + 8208 + 9474 = 19316.

    Find the sum of all the numbers that can be written as the sum of fifth 
    powers of their digits.
    """
    
    #The lowest number which will be tested. As in the example, 1 will not be
    #tested.
    low_range = 2
    
    #The highest number which will be tested. The highest number with six 
    #digits, 999,999 actually evaluates to a lower number than itself.
    #
    #9**5 * 6 = 354,294.
    #
    #This is the first number with only 9s among its digits to have this 
    #property. Numbers above it continue this trend, and therefore need not be 
    #tested.
    high_range = 10 ** 6
    
    def sum_of_fifth_power_of_digits(n):
        """Returns the sum of the fifth powers of the digits of [n]"""
        return sum(x ** 5 for x in integer_to_digits(n))
    
    #Return result        
    return sum(
              n for n in xrange(low_range, high_range) 
                if sum_of_fifth_power_of_digits(n) == n
            )
        
    
    
    
if __name__ == "__main__":
    cProfile.run("print(get_answer())")
